/**============================================================================
 *
 * Author: luo1o1o1o 
 *
 * QQ: 330240995, PHONE: 17600071321
 *
 * Last modified: 2021-06-01 17:58
 *
 * Filename: user.js
 *
 * Description: user servies
 *
 ============================================================================**/
const { User } = require('../db/model/index')
const { formatUser } = require('./_format')
const doCrypto = require('../utils/cryp')

/**
 * @Author: luo1o1o1o
 * @QQ: 330240995, @PHONE: 17600071321
 * @Date: 2021-06-01 18:16
 * @desc: 获取用户信息
 */
async function getUserInfo(userName, password) {
    // 查询条件
    const whereOpt = {
        userName,
    }
    if (password) {
        Object.assign(whereOpt, { password: doCrypto(password) })
    }
    // 查询
    const result = await User.findOne({
        attributes: ['id', 'userName', 'nickName', 'picture', 'city'], // 查询列
        where: whereOpt,
    })
    if (result == null) {
        // 未找到
        return result
    }
    // 格式化
    const formatRes = formatUser(result.dataValues)
    return formatRes
}

/**
 * @Author: luo1o1o1o
 * @QQ: 330240995, @PHONE: 17600071321
 * @Date: 2021-06-07 11:30
 * @desc: 创建用户
 */
async function createUser({ userName, password, gender = 3, nickName }) {
    const result = await User.create({
        userName,
        password,
        nickName: nickName ? nickName : userName,
        gender,
    })
    return result.dataValues
}

/**
 * @Author: luo1o1o1o
 * @QQ: 330240995, @PHONE: 17600071321
 * @Date: 2021-06-18 10:01
 * @desc: 删除用户
 */
async function deleteUser(userName) {
    const result = await User.destroy({
        where: {
            userName,
        },
    })
    // 返回删除的行数
    return result > 0
}

/**
 * @Author: luo1o1o1o
 * @Date: 2021-06-27 14:32
 * @param: {*} param0 修改的字段 { newPassword, newNickName, newPicture, newCity }
 * @param: {*} param1 查询的字段 { userName, password }
 */
async function updateUser(
    { newPassword, newNickName, newPicture, newCity },
    { userName, password }
) {
    // 拼接修改内容
    const updateData = {}
    if (newPassword) {
        updateData.password = newPassword
    }
    if (newNickName) {
        updateData.nickName = newNickName
    }
    if (newPicture) {
        updateData.picture = newPicture
    }
    if (newCity) {
        updateData.city = newCity
    }
    // 拼接查询条件
    const whereOpt = {
        userName,
    }
    if (password) {
        whereOpt.password = password
    }
    // 执行修改
    const result = await User.update(updateData, {
        where: whereOpt,
    })
    // 判断修改行数是否>1
    return result[0] > 0
}

module.exports = {
    getUserInfo,
    createUser,
    deleteUser,
    updateUser,
}
